// Copyright (C) 2024 Kumo inc.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#include <kllm/config/arg.h>
#include <kllm/utility/log.h>
#include <kllm/core/sampling.h>
#include <turbo/strings/str_format.h>
#include <turbo/strings/str_split.h>
#include <turbo/strings/uri.h>
#include <algorithm>
#include <climits>
#include <cstdarg>
#include <fstream>
#include <regex>
#include <set>
#include <string>
#include <thread>
#include <vector>
#include <kllm/core/km_context.h>
#include <kllm/utility/json_schema_to_grammar.h>
#include <kmfs/filesystem.hpp>

namespace kllm {

    using json = nlohmann::ordered_json;

    AppArgs &AppArgs::set_examples(std::initializer_list<enum llama_example> examples) {
        this->examples = std::move(examples);
        return *this;
    }

    AppArgs &AppArgs::set_env(const char *env) {
        help = help + "\n(env: " + env + ")";
        this->env = env;
        return *this;
    }

    AppArgs &AppArgs::set_sparam() {
        is_sparam = true;
        return *this;
    }

    bool AppArgs::in_example(enum llama_example ex) {
        return examples.find(ex) != examples.end();
    }

    bool AppArgs::get_value_from_env(std::string &output) {
        if (env.empty()) return false;
        char *value = std::getenv(env.c_str());
        if (value) {
            output = value;
            return true;
        }
        return false;
    }

    bool AppArgs::has_value_from_env() {
        return !env.empty() && std::getenv(env.c_str());
    }

    static std::vector<std::string> break_str_into_lines(std::string input, size_t max_char_per_line) {
        std::vector<std::string> result;
        std::istringstream iss(input);
        std::string line;
        auto add_line = [&](const std::string &l) {
            if (l.length() <= max_char_per_line) {
                result.push_back(l);
            } else {
                std::istringstream line_stream(l);
                std::string word, current_line;
                while (line_stream >> word) {
                    if (current_line.length() + !current_line.empty() + word.length() > max_char_per_line) {
                        if (!current_line.empty()) result.push_back(current_line);
                        current_line = word;
                    } else {
                        current_line += (!current_line.empty() ? " " : "") + word;
                    }
                }
                if (!current_line.empty()) result.push_back(current_line);
            }
        };
        while (std::getline(iss, line)) {
            add_line(line);
        }
        return result;
    }

    std::string AppArgs::to_string() {
        // params for printing to console
        const static int n_leading_spaces = 40;
        const static int n_char_per_line_help = 70; // TODO: detect this based on current console
        std::string leading_spaces(n_leading_spaces, ' ');

        std::ostringstream ss;
        ss << args;
        if (!value_hint.empty()) ss << " " << value_hint;
        if (!value_hint_2.empty()) ss << " " << value_hint_2;
        if (ss.tellp() > n_leading_spaces - 3) {
            // current line is too long, add new line
            ss << "\n" << leading_spaces;
        } else {
            // padding between arg and help, same line
            ss << std::string(leading_spaces.size() - ss.tellp(), ' ');
        }
        const auto help_lines = break_str_into_lines(help, n_char_per_line_help);
        for (const auto &line: help_lines) {
            ss << (&line == &help_lines.front() ? "" : leading_spaces) << line << "\n";
        }
        return ss.str();
    }


    static void common_params_handle_model_default(KMParams &params) {
        if (!params.hf_repo.empty()) {
            // short-hand to avoid specifying --hf-file -> default it to --model
            if (params.hf_file.empty()) {
                if (params.model.empty()) {
                    throw std::invalid_argument("error: --hf-repo requires either --hf-file or --model\n");
                }
                params.hf_file = params.model;
            } else if (params.model.empty()) {
                std::vector<std::string> files = turbo::str_split(params.hf_file, '/');
                params.model = fs_get_cache_file(files.back());
            }
        } else if (!params.model_url.empty()) {
            if (params.model.empty()) {
                turbo::Uri uri;
                uri.parse(params.model_url);
                params.model = fs_get_cache_file(kumo::filesystem::path(uri.path()).filename());
            }
        } else if (params.model.empty()) {
            params.model = DEFAULT_MODEL_PATH;
        }
    }

    void ParamsContext::add_option(AppArgs arg) {
        if (arg.in_example(ex) || arg.in_example(LLAMA_EXAMPLE_COMMON)) {
            options.push_back(std::move(arg));
        }
    }

    void params_parser_init(ParamsContext &ctx_arg, KMParams &params, llama_example ex) {
        ctx_arg.ex = ex;

        std::string sampler_type_chars;
        std::string sampler_type_names;
        for (const auto &sampler: params.sparams.samplers) {
            sampler_type_chars += common_sampler_type_to_chr(static_cast<KaiSamplerType>(sampler));
            sampler_type_names += common_sampler_type_to_str(static_cast<KaiSamplerType>(sampler)) + ";";
        }
        sampler_type_names.pop_back();


        /**
         * filter options by example
         * rules:
         * - all examples inherit options from LLAMA_EXAMPLE_COMMON
         * - if LLAMA_EXAMPLE_* is set (other than COMMON), we only show the option in the corresponding example
         * - if both {LLAMA_EXAMPLE_COMMON, LLAMA_EXAMPLE_*,} are set, we will prioritize the LLAMA_EXAMPLE_* matching current example
         */

        ctx_arg.add_option(AppArgs(
                "--verbose-prompt",
                turbo::str_format("print a verbose prompt before generation (default: %s)",
                                  params.verbose_prompt ? "true" : "false"),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args,
                                  [&params](int64_t) {
                                      params.verbose_prompt = true;
                                  },
                                  args.help
                    );
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--no-display-prompt",
                turbo::str_format("don't print prompt at generation (default: %s)",
                                  !params.display_prompt ? "true" : "false"),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args,
                                  [&params](int64_t) {
                                      params.display_prompt = false;
                                  },
                                  args.help
                    );
                }
        ).set_examples({LLAMA_EXAMPLE_MAIN}));
        ctx_arg.add_option(AppArgs(
                "--color",
                turbo::str_format("colorise output to distinguish prompt and user input from generations (default: %s)",
                                  params.use_color ? "true" : "false"),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args,
                                  [&params](int64_t) {
                                      params.use_color = true;
                                  },
                                  args.help
                    );
                }
        ).set_examples({LLAMA_EXAMPLE_MAIN, LLAMA_EXAMPLE_INFILL, LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_LOOKUP}));
        ctx_arg.add_option(AppArgs(
                "-t,--threads", "N",
                turbo::str_format("number of threads to use during generation (default: %d)",
                                  params.cpuparams.n_threads),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.cpuparams.n_threads, args.help)
                            ->default_val(std::thread::hardware_concurrency())
                            ->expected(1, 100000)->envname("LLAMA_ARG_THREADS");
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--threads-batch", "N",
                "number of threads to use during batch and prompt processing (default: same as --threads)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.cpuparams_batch.n_threads, args.help)
                            ->default_val(std::thread::hardware_concurrency())
                            ->expected(1, 100000);
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--threads-draft", "N",
                "number of threads to use during generation (default: same as --threads)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.draft_cpuparams.n_threads, args.help)
                            ->default_val(std::thread::hardware_concurrency())
                            ->expected(1, 100000);
                }
        ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
        ctx_arg.add_option(AppArgs(
                "--threads-batch-draft", "N",
                "number of threads to use during batch and prompt processing (default: same as --threads-draft)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.draft_cpuparams_batch.n_threads, args.help)
                            ->default_val(std::thread::hardware_concurrency())
                            ->expected(1, 100000);

                }
        ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
        ctx_arg.add_option(AppArgs(
                "--cpu-mask", "M",
                "CPU affinity mask: arbitrarily long hex. Complements cpu-range (default: \"\")",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &mask) {
                                                              params.cpuparams.mask_valid = true;
                                                              if (!parse_cpu_mask(mask, params.cpuparams.cpumask)) {
                                                                  throw std::invalid_argument("invalid cpumask");
                                                              }
                                                          },
                                                          args.help
                    );
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--cpu-range", "lo-hi",
                "range of CPUs for affinity. Complements --cpu-mask",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &range) {
                                                              params.cpuparams.mask_valid = true;
                                                              if (!parse_cpu_range(range, params.cpuparams.cpumask)) {
                                                                  throw std::invalid_argument("invalid range");
                                                              }
                                                          },
                                                          args.help
                    );
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--cpu-strict", "<0|1>",
                turbo::str_format("use strict CPU placement (default: %u)\n", (unsigned) params.cpuparams.strict_cpu),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.cpuparams.strict_cpu, args.help);
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--prio", "N",
                turbo::str_format(
                        "set process/thread priority : 0-normal, 1-medium, 2-high, 3-realtime (default: %d)\n",
                        params.cpuparams.priority),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.cpuparams.priority, args.help)
                            ->expected(0, 3);
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--poll", "<0...100>",
                turbo::str_format("use polling level to wait for work (0 - no polling, default: %u)\n",
                                  (unsigned) params.cpuparams.poll),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.cpuparams.poll, args.help);
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--cpu-mask-batch", "M",
                "CPU affinity mask: arbitrarily long hex. Complements cpu-range-batch (default: same as --cpu-mask)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &mask) {
                                                              params.cpuparams_batch.mask_valid = true;
                                                              if (!parse_cpu_mask(mask,
                                                                                  params.cpuparams_batch.cpumask)) {
                                                                  throw std::invalid_argument("invalid cpumask");
                                                              }
                                                          },
                                                          args.help
                    );
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--cpu-range-batch", "lo-hi",
                "ranges of CPUs for affinity. Complements --cpu-mask-batch",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &range) {
                                                              params.cpuparams_batch.mask_valid = true;
                                                              if (!parse_cpu_range(range,
                                                                                   params.cpuparams_batch.cpumask)) {
                                                                  throw std::invalid_argument("invalid range");
                                                              }
                                                          },
                                                          args.help
                    );
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--cpu-strict-batch", "<0|1>",
                "use strict CPU placement (default: same as --cpu-strict)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.cpuparams_batch.strict_cpu, args.help);
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--prio-batch", "N",
                turbo::str_format(
                        "set process/thread priority : 0-normal, 1-medium, 2-high, 3-realtime (default: %d)\n",
                        params.cpuparams_batch.priority),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.cpuparams_batch.priority, args.help)
                            ->expected(0, 3);
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--poll-batch", "<0|1>",
                "use polling to wait for work (default: same as --poll)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.cpuparams_batch.poll, args.help);
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--cpu-mask-draft", "M",
                "Draft model CPU affinity mask. Complements cpu-range-draft (default: same as --cpu-mask)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &mask) {
                                                              params.draft_cpuparams.mask_valid = true;
                                                              if (!parse_cpu_mask(mask,
                                                                                  params.draft_cpuparams.cpumask)) {
                                                                  throw std::invalid_argument("invalid cpumask");
                                                              }
                                                          },
                                                          args.help
                    );
                }
        ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
        ctx_arg.add_option(AppArgs(
                "--cpu-range-draft", "lo-hi",
                "Ranges of CPUs for affinity. Complements --cpu-mask-draft",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {

                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &range) {
                                                              params.draft_cpuparams.mask_valid = true;
                                                              if (!parse_cpu_range(range,
                                                                                   params.draft_cpuparams.cpumask)) {
                                                                  throw std::invalid_argument("invalid range");
                                                              }
                                                          },
                                                          args.help
                    );
                }
        ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
        ctx_arg.add_option(AppArgs(
                "--cpu-strict-draft", "<0|1>",
                "Use strict CPU placement for draft model (default: same as --cpu-strict)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.draft_cpuparams.strict_cpu, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
        ctx_arg.add_option(AppArgs(
                "--prio-draft", "N",
                turbo::str_format(
                        "set draft process/thread priority : 0-normal, 1-medium, 2-high, 3-realtime (default: %d)\n",
                        params.draft_cpuparams.priority),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.draft_cpuparams.priority, args.help)
                            ->expected(0, 3);
                }
        ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
        ctx_arg.add_option(AppArgs(
                "--poll-draft", "<0|1>",
                "Use polling to wait for draft model work (default: same as --poll])",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.draft_cpuparams.poll, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
        ctx_arg.add_option(AppArgs(
                "--cpu-mask-batch-draft", "M",
                "Draft model CPU affinity mask. Complements cpu-range-draft (default: same as --cpu-mask)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &mask) {
                                                              params.draft_cpuparams_batch.mask_valid = true;
                                                              if (!parse_cpu_mask(mask,
                                                                                  params.draft_cpuparams_batch.cpumask)) {
                                                                  throw std::invalid_argument("invalid cpumask");
                                                              }
                                                          },
                                                          args.help
                    );
                }
        ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
        ctx_arg.add_option(AppArgs(
                "--cpu-range-batch-draft", "lo-hi",
                "Ranges of CPUs for affinity. Complements --cpu-mask-draft-batch)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &range) {
                                                              params.draft_cpuparams_batch.mask_valid = true;
                                                              if (!parse_cpu_range(range,
                                                                                   params.draft_cpuparams_batch.cpumask)) {
                                                                  throw std::invalid_argument("invalid range");
                                                              }
                                                          },
                                                          args.help
                    );
                }
        ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
        ctx_arg.add_option(AppArgs(
                "--cpu-strict-batch-draft", "<0|1>",
                "Use strict CPU placement for draft model (default: --cpu-strict-draft)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.draft_cpuparams_batch.strict_cpu, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
        ctx_arg.add_option(AppArgs(
                "--prio-batch-draft", "N",
                turbo::str_format(
                        "set draft process/thread priority : 0-normal, 1-medium, 2-high, 3-realtime (default: %d)\n",
                        params.draft_cpuparams_batch.priority),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.draft_cpuparams_batch.priority, args.help)
                            ->expected(0, 3);
                }
        ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
        ctx_arg.add_option(AppArgs(
                "--poll-batch-draft", "<0|1>",
                "Use polling to wait for draft model work (default: --poll-draft)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.draft_cpuparams_batch.poll, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
        ctx_arg.add_option(AppArgs(
                "--draft", "N",
                turbo::str_format("number of tokens to draft for speculative decoding (default: %d)", params.n_draft),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.n_draft, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_LOOKUP}));
        ctx_arg.add_option(AppArgs(
                "-ps", "--p-split", "N",
                turbo::str_format("speculative decoding split probability (default: %.1f)", (double) params.p_split),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.p_split, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
        ctx_arg.add_option(AppArgs(
                "--lookup-cache-static", "FNAME",
                "path to static lookup cache to use for lookup decoding (not updated by generation)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.lookup_cache_static, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_LOOKUP}));
        ctx_arg.add_option(AppArgs(
                "--lookup-cache-dynamic", "FNAME",
                "path to dynamic lookup cache to use for lookup decoding (updated by generation)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.lookup_cache_dynamic, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_LOOKUP}));
        ctx_arg.add_option(AppArgs(
                "-c,--ctx-size", "N",
                turbo::str_format("size of the prompt context (default: %d, 0 = loaded from model)", params.n_ctx),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.n_ctx, args.help)->envname("LLAMA_ARG_CTX_SIZE");
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--predict", "N",
                turbo::str_format("number of tokens to predict (default: %d, -1 = infinity, -2 = until context filled)",
                                  params.n_predict),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.n_predict, args.help)->envname("LLAMA_ARG_N_PREDICT");
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--batch-size", "N",
                turbo::str_format("logical maximum batch size (default: %d)", params.n_batch),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.n_batch, args.help);
                }
        ).set_env("LLAMA_ARG_BATCH"));
        ctx_arg.add_option(AppArgs(
                "--ubatch-size", "N",
                turbo::str_format("physical maximum batch size (default: %d)", params.n_ubatch),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.n_ubatch, args.help);
                }
        ).set_env("LLAMA_ARG_UBATCH"));
        ctx_arg.add_option(AppArgs(
                "--keep", "N",
                turbo::str_format("number of tokens to keep from the initial prompt (default: %d, -1 = all)",
                                  params.n_keep),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.n_keep, args.help);
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--no-context-shift",
                turbo::str_format("disables context shift on inifinite text generation (default: %s)",
                                  params.ctx_shift ? "disabled" : "enabled"),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) { params.ctx_shift = true; }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_MAIN, LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_NO_CONTEXT_SHIFT"));
        ctx_arg.add_option(AppArgs(
                "--chunks", "N",
                turbo::str_format("max number of chunks to process (default: %d, -1 = all)", params.n_chunks),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.n_chunks, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_IMATRIX, LLAMA_EXAMPLE_PERPLEXITY, LLAMA_EXAMPLE_RETRIEVAL}));
        ctx_arg.add_option(AppArgs(
                "--flash-attn",
                turbo::str_format("enable Flash Attention (default: %s)", params.flash_attn ? "enabled" : "disabled"),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    params.flash_attn = true;
                    app->add_flag(args.args, [&params](int64_t) { params.flash_attn = true; }, args.help);
                }
        ).set_env("LLAMA_ARG_FLASH_ATTN"));
        ctx_arg.add_option(AppArgs(
                "-p,--prompt", "PROMPT",
                ex == LLAMA_EXAMPLE_MAIN
                ? "prompt to start generation with\nif -cnv is set, this will be used as system prompt"
                : "prompt to start generation with",
                [&ctx_arg](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.prompt, args.help);
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--no-perf",
                turbo::str_format("disable internal libllama performance timings (default: %s)",
                                  params.no_perf ? "true" : "false"),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.no_perf = true;
                        params.sparams.no_perf = true;
                    }, args.help);
                }
        ).set_env("LLAMA_ARG_NO_PERF"));
        ctx_arg.add_option(AppArgs(
                "-f, --file", "FNAME",
                "a file containing the prompt (default: none)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {

                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              std::ifstream file(value);
                                                              if (!file) {
                                                                  throw std::runtime_error(turbo::str_format(
                                                                          "error: failed to open file '%s'\n",
                                                                          value.c_str()));
                                                              }
                                                              // store the external file name in params
                                                              params.prompt_file = value;
                                                              std::copy(std::istreambuf_iterator<char>(file),
                                                                        std::istreambuf_iterator<char>(),
                                                                        back_inserter(params.prompt));
                                                              if (!params.prompt.empty() &&
                                                                  params.prompt.back() == '\n') {
                                                                  params.prompt.pop_back();
                                                              }
                                                          },
                                                          args.help
                    );
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--in-file", "FNAME",
                "an input file (repeat to specify multiple files)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {

                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              std::ifstream file(value);
                                                              if (!file) {
                                                                  throw std::runtime_error(turbo::str_format(
                                                                          "error: failed to open file '%s'\n",
                                                                          value.c_str()));
                                                              }
                                                              params.in_files.push_back(value);
                                                          },
                                                          args.help
                    );
                }
        ).set_examples({LLAMA_EXAMPLE_IMATRIX}));
        ctx_arg.add_option(AppArgs(
                "--binary-file", "FNAME",
                "binary file containing the prompt (default: none)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              std::ifstream file(value, std::ios::binary);
                                                              if (!file) {
                                                                  throw std::runtime_error(turbo::str_format(
                                                                          "error: failed to open file '%s'\n",
                                                                          value.c_str()));
                                                              }
                                                              // store the external file name in params
                                                              params.prompt_file = value;
                                                              std::ostringstream ss;
                                                              ss << file.rdbuf();
                                                              params.prompt = ss.str();
                                                              fprintf(stderr, "Read %zu bytes from binary file %s\n",
                                                                      params.prompt.size(), value.c_str());
                                                          },
                                                          args.help
                    );
                }
        ));
        ctx_arg.add_option(AppArgs(
                "-e,--escape",
                turbo::str_format("process escapes sequences (\\n, \\r, \\t, \\', \\\", \\\\) (default: %s)",
                                  params.escape ? "true" : "false"),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.escape = true;
                    }, args.help);
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--no-escape",
                "do not process escape sequences",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    params.escape = false;
                    app->add_flag(args.args, [&params](int64_t) {
                        params.escape = false;
                    }, args.help);
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--print-token-count", "N",
                turbo::str_format("print token count every N tokens (default: %d)", params.n_print),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.n_print, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_MAIN}));
        ctx_arg.add_option(AppArgs(
                "--prompt-cache", "FNAME",
                "file to cache prompt state for faster startup (default: none)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.path_prompt_cache, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_MAIN}));
        ctx_arg.add_option(AppArgs(
                "--prompt-cache-all",
                "if specified, saves user input and generations to cache as well\n",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.prompt_cache_all = true;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_MAIN}));
        ctx_arg.add_option(AppArgs(
                "--prompt-cache-ro",
                "if specified, uses the prompt cache but does not update it",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.prompt_cache_ro = true;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_MAIN}));
        ctx_arg.add_option(AppArgs(
                "-r,--reverse-prompt", "PROMPT",
                "halt generation at PROMPT, return control in interactive mode\n",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.antiprompt, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_MAIN}));
        ctx_arg.add_option(AppArgs(
                "--special",
                turbo::str_format("special tokens output enabled (default: %s)", params.special ? "true" : "false"),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.special = true;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_MAIN, LLAMA_EXAMPLE_SERVER}));
        ctx_arg.add_option(AppArgs(
                "--conversation",
                turbo::str_format(
                        "run in conversation mode:\n"
                        "- does not print special tokens and suffix/prefix\n"
                        "- interactive mode is also enabled\n"
                        "(default: %s)",
                        params.conversation ? "true" : "false"
                ),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.conversation = true;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_MAIN}));
        ctx_arg.add_option(AppArgs(
                "-i,--interactive",
                turbo::str_format("run in interactive mode (default: %s)", params.interactive ? "true" : "false"),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.interactive = true;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_MAIN}));
        ctx_arg.add_option(AppArgs(
                "--interactive-first",
                turbo::str_format("run in interactive mode and wait for input right away (default: %s)",
                                  params.interactive_first ? "true" : "false"),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.interactive_first = true;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_MAIN}));
        ctx_arg.add_option(AppArgs(
                "--multiline-input",
                "allows you to write or paste multiple lines without ending each in '\\'",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.multiline_input = true;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_MAIN}));
        ctx_arg.add_option(AppArgs(
                "--in-prefix-bos",
                "prefix BOS to user inputs, preceding the `--in-prefix` string",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.input_prefix_bos = true;
                        params.enable_chat_template = false;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_MAIN}));
        ctx_arg.add_option(AppArgs(
                "--in-prefix", "STRING",
                "string to prefix user inputs with (default: empty)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              params.input_prefix = value;
                                                              params.enable_chat_template = false;
                                                          },
                                                          args.help
                    );
                }
        ).set_examples({LLAMA_EXAMPLE_MAIN, LLAMA_EXAMPLE_INFILL}));
        ctx_arg.add_option(AppArgs(
                "--in-suffix", "STRING",
                "string to suffix after user inputs with (default: empty)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              params.input_suffix = value;
                                                              params.enable_chat_template = false;
                                                          },
                                                          args.help
                    );
                }
        ).set_examples({LLAMA_EXAMPLE_MAIN, LLAMA_EXAMPLE_INFILL}));
        ctx_arg.add_option(AppArgs(
                "--no-warmup",
                "skip warming up the model with an empty run",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.warmup = false;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_MAIN}));
        ctx_arg.add_option(AppArgs(
                "--spm-infill",
                turbo::str_format(
                        "use Suffix/Prefix/Middle pattern for infill (instead of Prefix/Suffix/Middle) as some models prefer this. (default: %s)",
                        params.spm_infill ? "enabled" : "disabled"
                ),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.spm_infill = true;
                    }, args.help);

                }
        ).set_examples({LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_INFILL}));
        ctx_arg.add_option(AppArgs(
                "--samplers", "SAMPLERS",
                turbo::str_format(
                        "samplers that will be used for generation in the order, separated by \';\'\n(default: %s)",
                        sampler_type_names.c_str()),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              const auto sampler_names = turbo::str_split(value, ';');
                                                              params.sparams.samplers = common_sampler_types_from_names(
                                                                      sampler_names, true);
                                                          },
                                                          args.help
                    );
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "-s, --seed", "SEED",
                turbo::str_format("RNG seed (default: %d, use random seed for %d)", params.sparams.seed,
                                  LLAMA_DEFAULT_SEED),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.sparams.seed, args.help);
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--sampling-seq", "SEQUENCE",
                turbo::str_format("simplified sequence for samplers that will be used (default: %s)",
                                  sampler_type_chars.c_str()),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              params.sparams.samplers = common_sampler_types_from_chars(
                                                                      value);
                                                          },
                                                          args.help
                    );
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--ignore-eos",
                "ignore end of stream token and continue generating (implies --logit-bias EOS-inf)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.sparams.ignore_eos = true;
                    }, args.help);
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--penalize-nl",
                turbo::str_format("penalize newline tokens (default: %s)",
                                  params.sparams.penalize_nl ? "true" : "false"),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.sparams.penalize_nl = true;
                    }, args.help);
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--temp", "N",
                turbo::str_format("temperature (default: %.1f)", (double) params.sparams.temp),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              params.sparams.temp = std::stof(value);
                                                              params.sparams.temp = std::max(params.sparams.temp, 0.0f);
                                                          },
                                                          args.help
                    );
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--top-k", "N",
                turbo::str_format("top-k sampling (default: %d, 0 = disabled)", params.sparams.top_k),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.sparams.top_k, args.help);
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--top-p", "N",
                turbo::str_format("top-p sampling (default: %.1f, 1.0 = disabled)", (double) params.sparams.top_p),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.sparams.top_p, args.help);
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--min-p", "N",
                turbo::str_format("min-p sampling (default: %.1f, 0.0 = disabled)", (double) params.sparams.min_p),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.sparams.min_p, args.help);
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--xtc-probability", "N",
                turbo::str_format("xtc probability (default: %.1f, 0.0 = disabled)",
                                  (double) params.sparams.xtc_probability),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.sparams.xtc_probability, args.help);
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--xtc-threshold", "N",
                turbo::str_format("xtc threshold (default: %.1f, 1.0 = disabled)",
                                  (double) params.sparams.xtc_threshold),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.sparams.xtc_threshold, args.help);
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--typical", "N",
                turbo::str_format("locally typical sampling, parameter p (default: %.1f, 1.0 = disabled)",
                                  (double) params.sparams.typ_p),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.sparams.typ_p, args.help);
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--repeat-last-n", "N",
                turbo::str_format("last n tokens to consider for penalize (default: %d, 0 = disabled, -1 = ctx_size)",
                                  params.sparams.penalty_last_n),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {

                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              params.sparams.penalty_last_n = std::atoi(value.c_str());
                                                              params.sparams.n_prev = std::max(params.sparams.n_prev,
                                                                                               params.sparams.penalty_last_n);
                                                          },
                                                          args.help
                    );
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--repeat-penalty", "N",
                turbo::str_format("penalize repeat sequence of tokens (default: %.1f, 1.0 = disabled)",
                                  (double) params.sparams.penalty_repeat),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.sparams.penalty_repeat, args.help);
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--presence-penalty", "N",
                turbo::str_format("repeat alpha presence penalty (default: %.1f, 0.0 = disabled)",
                                  (double) params.sparams.penalty_present),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.sparams.penalty_present, args.help);
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--frequency-penalty", "N",
                turbo::str_format("repeat alpha frequency penalty (default: %.1f, 0.0 = disabled)",
                                  (double) params.sparams.penalty_freq),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.sparams.penalty_freq, args.help);
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--dry-multiplier", "N",
                turbo::str_format("set DRY sampling multiplier (default: %.1f, 0.0 = disabled)",
                                  (double) params.sparams.dry_multiplier),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.sparams.dry_multiplier, args.help);
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--dry-base", "N",
                turbo::str_format("set DRY sampling base value (default: %.2f)", (double) params.sparams.dry_base),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              float potential_base = std::stof(value);
                                                              if (potential_base >= 1.0f) {
                                                                  params.sparams.dry_base = potential_base;
                                                              }
                                                          },
                                                          args.help
                    );
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--dry-allowed-length", "N",
                turbo::str_format("set allowed length for DRY sampling (default: %d)",
                                  params.sparams.dry_allowed_length),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.sparams.dry_allowed_length, args.help);
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--dry-penalty-last-n", "N",
                turbo::str_format("set DRY penalty for the last n tokens (default: %d, 0 = disable, -1 = context size)",
                                  params.sparams.dry_penalty_last_n),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.sparams.dry_penalty_last_n, args.help);
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--dry-sequence-breaker", "STRING",
                turbo::str_format(
                        "add sequence breaker for DRY sampling, clearing out default breakers (%s) in the process; use \"none\" to not use any sequence breakers\n",
                        params.sparams.dry_sequence_breakers.empty() ? "none" :
                        std::accumulate(std::next(params.sparams.dry_sequence_breakers.begin()),
                                        params.sparams.dry_sequence_breakers.end(),
                                        std::string("'") + (params.sparams.dry_sequence_breakers[0] == "\n" ? "\\n"
                                                                                                            : params.sparams.dry_sequence_breakers[0]) +
                                        "'",
                                        [](const std::string &a, const std::string &b) {
                                            std::string formatted_b = (b == "\n") ? "\\n" : b;
                                            return a + ", '" + formatted_b + "'";
                                        }).c_str()),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {

                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              static bool defaults_cleared = false;
                                                              if (!defaults_cleared) {
                                                                  params.sparams.dry_sequence_breakers.clear();
                                                                  defaults_cleared = true;
                                                              }

                                                              if (value == "none") {
                                                                  params.sparams.dry_sequence_breakers.clear();
                                                              } else {
                                                                  params.sparams.dry_sequence_breakers.push_back(value);
                                                              }
                                                          },
                                                          args.help
                    );
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--dynatemp-range", "N",
                turbo::str_format("dynamic temperature range (default: %.1f, 0.0 = disabled)",
                                  (double) params.sparams.dynatemp_range),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.sparams.dynatemp_range, args.help);
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--dynatemp-exp", "N",
                turbo::str_format("dynamic temperature exponent (default: %.1f)",
                                  (double) params.sparams.dynatemp_exponent),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.sparams.dynatemp_exponent, args.help);
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--mirostat", "N",
                turbo::str_format(
                        "use Mirostat sampling.\nTop K, Nucleus and Locally Typical samplers are ignored if used.\n"
                        "(default: %d, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)", params.sparams.mirostat),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.sparams.mirostat, args.help);
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--mirostat-lr", "N",
                turbo::str_format("Mirostat learning rate, parameter eta (default: %.1f)",
                                  (double) params.sparams.mirostat_eta),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.sparams.mirostat_eta, args.help);
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--mirostat-ent", "N",
                turbo::str_format("Mirostat target entropy, parameter tau (default: %.1f)",
                                  (double) params.sparams.mirostat_tau),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.sparams.mirostat_tau, args.help);
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "-l, --logit-bias", "TOKEN_ID(+/-)BIAS",
                "modifies the likelihood of token appearing in the completion,\n"
                "i.e. `--logit-bias 15043+1` to increase likelihood of token ' Hello',\n"
                "or `--logit-bias 15043-1` to decrease likelihood of token ' Hello'",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              std::stringstream ss(value);
                                                              llama_token key;
                                                              char sign;
                                                              std::string value_str;
                                                              try {
                                                                  if (ss >> key && ss >> sign &&
                                                                      std::getline(ss, value_str) &&
                                                                      (sign == '+' || sign == '-')) {
                                                                      const float bias = std::stof(value_str) *
                                                                                         ((sign == '-') ? -1.0f : 1.0f);
                                                                      params.sparams.logit_bias.push_back({key, bias});
                                                                  } else {
                                                                      throw std::invalid_argument(
                                                                              "invalid input format");
                                                                  }
                                                              } catch (const std::exception &) {
                                                                  throw std::invalid_argument("invalid input format");
                                                              }
                                                          },
                                                          args.help
                    );
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--grammar", "GRAMMAR",
                turbo::str_format(
                        "BNF-like grammar to constrain generations (see samples in grammars/ dir) (default: '%s')",
                        params.sparams.grammar.c_str()),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.sparams.grammar, args.help);
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--grammar-file", "FNAME",
                "file to read grammar from",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              std::ifstream file(value);
                                                              if (!file) {
                                                                  throw std::runtime_error(turbo::str_format(
                                                                          "error: failed to open file '%s'\n",
                                                                          value.c_str()));
                                                              }
                                                              std::string gg;
                                                              std::copy(
                                                                      std::istreambuf_iterator<char>(file),
                                                                      std::istreambuf_iterator<char>(),
                                                                      std::back_inserter(gg)

                                                              );

                                                              params.sparams.grammar = gg;
                                                          },
                                                          args.help
                    );
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "-j,--json-schema", "SCHEMA",
                "JSON schema to constrain generations (https://json-schema.org/), e.g. `{}` for any JSON object\nFor schemas w/ external $refs, use --grammar + example/json_schema_to_grammar.py instead",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              params.sparams.grammar = json_schema_to_grammar(
                                                                      json::parse(value));
                                                          },
                                                          args.help
                    );
                }
        ).set_sparam());
        ctx_arg.add_option(AppArgs(
                "--pooling", "{none,mean,cls,last,rank}",
                "pooling type for embeddings, use model default if unspecified",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {

                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              if (value ==
                                                                  "none") { params.pooling_type = LLAMA_POOLING_TYPE_NONE; }
                                                              else if (value ==
                                                                       "mean") { params.pooling_type = LLAMA_POOLING_TYPE_MEAN; }
                                                              else if (value ==
                                                                       "cls") { params.pooling_type = LLAMA_POOLING_TYPE_CLS; }
                                                              else if (value ==
                                                                       "last") { params.pooling_type = LLAMA_POOLING_TYPE_LAST; }
                                                              else if (value ==
                                                                       "rank") { params.pooling_type = LLAMA_POOLING_TYPE_RANK; }
                                                              else { throw std::invalid_argument("invalid value"); }
                                                          },
                                                          args.help
                    );
                }
        ).set_examples({LLAMA_EXAMPLE_EMBEDDING, LLAMA_EXAMPLE_RETRIEVAL, LLAMA_EXAMPLE_SERVER}).set_env(
                "LLAMA_ARG_POOLING"));
        ctx_arg.add_option(AppArgs(
                "--attention", "{causal,non-causal}",
                "attention type for embeddings, use model default if unspecified",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              if (value ==
                                                                  "causal") { params.attention_type = LLAMA_ATTENTION_TYPE_CAUSAL; }
                                                              else if (value ==
                                                                       "non-causal") { params.attention_type = LLAMA_ATTENTION_TYPE_NON_CAUSAL; }
                                                              else { throw std::invalid_argument("invalid value"); }
                                                          },
                                                          args.help
                    );
                }
        ).set_examples({LLAMA_EXAMPLE_EMBEDDING}));
        ctx_arg.add_option(AppArgs(
                "--rope-scaling", "{none,linear,yarn}",
                "RoPE frequency scaling method, defaults to linear unless specified by the model",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              if (value ==
                                                                  "none") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_NONE; }
                                                              else if (value ==
                                                                       "linear") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_LINEAR; }
                                                              else if (value ==
                                                                       "yarn") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_YARN; }
                                                              else { throw std::invalid_argument("invalid value"); }
                                                          },
                                                          args.help
                    );
                }
        ).set_env("LLAMA_ARG_ROPE_SCALING_TYPE"));
        ctx_arg.add_option(AppArgs(
                "--rope-scale", "N",
                "RoPE context scaling factor, expands context by a factor of N",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              params.rope_freq_scale = 1.0f / std::stof(value);
                                                          },
                                                          args.help
                    );
                }
        ).set_env("LLAMA_ARG_ROPE_SCALE"));
        ctx_arg.add_option(AppArgs(
                "--rope-freq-base", "N",
                "RoPE base frequency, used by NTK-aware scaling (default: loaded from model)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.rope_freq_base, args.help);
                }
        ).set_env("LLAMA_ARG_ROPE_FREQ_BASE"));
        ctx_arg.add_option(AppArgs(
                "--rope-freq-scale", "N",
                "RoPE frequency scaling factor, expands context by a factor of 1/N",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.rope_freq_scale, args.help);
                }
        ).set_env("LLAMA_ARG_ROPE_FREQ_SCALE"));
        ctx_arg.add_option(AppArgs(
                "--yarn-orig-ctx", "N",
                turbo::str_format("YaRN: original context size of model (default: %d = model training context size)",
                                  params.yarn_orig_ctx),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.yarn_orig_ctx, args.help);
                }
        ).set_env("LLAMA_ARG_YARN_ORIG_CTX"));
        ctx_arg.add_option(AppArgs(
                "--yarn-ext-factor", "N",
                turbo::str_format("YaRN: extrapolation mix factor (default: %.1f, 0.0 = full interpolation)",
                                  (double) params.yarn_ext_factor),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.yarn_ext_factor, args.help);
                }
        ).set_env("LLAMA_ARG_YARN_EXT_FACTOR"));
        ctx_arg.add_option(AppArgs(
                "--yarn-attn-factor", "N",
                turbo::str_format("YaRN: scale sqrt(t) or attention magnitude (default: %.1f)",
                                  (double) params.yarn_attn_factor),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.yarn_attn_factor, args.help);
                }
        ).set_env("LLAMA_ARG_YARN_ATTN_FACTOR"));
        ctx_arg.add_option(AppArgs(
                "--yarn-beta-slow", "N",
                turbo::str_format("YaRN: high correction dim or alpha (default: %.1f)", (double) params.yarn_beta_slow),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.yarn_beta_slow, args.help);
                }
        ).set_env("LLAMA_ARG_YARN_BETA_SLOW"));
        ctx_arg.add_option(AppArgs(
                "--yarn-beta-fast", "N",
                turbo::str_format("YaRN: low correction dim or beta (default: %.1f)", (double) params.yarn_beta_fast),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.yarn_beta_fast, args.help);
                }
        ).set_env("LLAMA_ARG_YARN_BETA_FAST"));
        ctx_arg.add_option(AppArgs(
                "--grp-attn-n", "N",
                turbo::str_format("group-attention factor (default: %d)", params.grp_attn_n),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.grp_attn_n, args.help);
                }
        ).set_env("LLAMA_ARG_GRP_ATTN_N").set_examples({LLAMA_EXAMPLE_MAIN, LLAMA_EXAMPLE_PASSKEY}));
        ctx_arg.add_option(AppArgs(
                "--grp-attn-w", "N",
                turbo::str_format("group-attention width (default: %d)", params.grp_attn_w),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.grp_attn_w, args.help);
                }
        ).set_env("LLAMA_ARG_GRP_ATTN_W").set_examples({LLAMA_EXAMPLE_MAIN}));
        ctx_arg.add_option(AppArgs(
                "--dump-kv-cache",
                "verbose print of the KV cache",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.dump_kv_cache = true;
                    }, args.help);
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--no-kv-offload",
                "disable KV offload",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.no_kv_offload = true;
                    }, args.help);
                }
        ).set_env("LLAMA_ARG_NO_KV_OFFLOAD"));
        ctx_arg.add_option(AppArgs(
                "--cache-type-k", "TYPE",
                turbo::str_format("KV cache data type for K (default: %s)", params.cache_type_k.c_str()),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    // TODO: get the type right here
                    app->add_option(args.args, params.cache_type_k, args.help);
                }
        ).set_env("LLAMA_ARG_CACHE_TYPE_K"));
        ctx_arg.add_option(AppArgs(
                "--cache-type-v", "TYPE",
                turbo::str_format("KV cache data type for V (default: %s)", params.cache_type_v.c_str()),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    // TODO: get the type right here
                    app->add_option(args.args, params.cache_type_v, args.help);
                }
        ).set_env("LLAMA_ARG_CACHE_TYPE_V"));
        ctx_arg.add_option(AppArgs(
                "--all-logits",
                turbo::str_format("return logits for all tokens in the batch (default: %s)",
                                  params.logits_all ? "true" : "false"),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.logits_all = true;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
        ctx_arg.add_option(AppArgs(
                "--hellaswag",
                "compute HellaSwag score over random tasks from datafile supplied with -f",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    params.hellaswag = true;
                    app->add_flag(args.args, [&params](int64_t) {
                        params.hellaswag = true;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
        ctx_arg.add_option(AppArgs(
                "--hellaswag-tasks", "N",
                turbo::str_format("number of tasks to use when computing the HellaSwag score (default: %zu)",
                                  params.hellaswag_tasks),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.hellaswag_tasks, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
        ctx_arg.add_option(AppArgs(
                "--winogrande",
                "compute Winogrande score over random tasks from datafile supplied with -f",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.winogrande = true;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
        ctx_arg.add_option(AppArgs(
                "--winogrande-tasks", "N",
                turbo::str_format("number of tasks to use when computing the Winogrande score (default: %zu)",
                                  params.winogrande_tasks),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.winogrande_tasks, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
        ctx_arg.add_option(AppArgs(
                "--multiple-choice",
                "compute multiple choice score over random tasks from datafile supplied with -f",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.multiple_choice = true;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
        ctx_arg.add_option(AppArgs(
                "--multiple-choice-tasks", "N",
                turbo::str_format("number of tasks to use when computing the multiple choice score (default: %zu)",
                                  params.multiple_choice_tasks),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.multiple_choice_tasks, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
        ctx_arg.add_option(AppArgs(
                "--kl-divergence",
                "computes KL-divergence to logits provided via --kl-divergence-base",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    params.kl_divergence = true;
                    app->add_flag(args.args, [&params](int64_t) {
                        params.kl_divergence = true;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
        ctx_arg.add_option(AppArgs(
                "--save-all-logits", "FNAME",
                "set logits file",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.logits_file, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
        ctx_arg.add_option(AppArgs(
                "--ppl-stride", "N",
                turbo::str_format("stride for perplexity calculation (default: %d)", params.ppl_stride),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.ppl_stride, args.help);

                }
        ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
        ctx_arg.add_option(AppArgs(
                "--ppl-output-type", "<0|1>",
                turbo::str_format("output type for perplexity calculation (default: %d)", params.ppl_output_type),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.ppl_output_type, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
        ctx_arg.add_option(AppArgs(
                "--defrag-thold", "N",
                turbo::str_format("KV cache defragmentation threshold (default: %.1f, < 0 - disabled)",
                                  (double) params.defrag_thold),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.defrag_thold, args.help);
                }
        ).set_env("LLAMA_ARG_DEFRAG_THOLD"));
        ctx_arg.add_option(AppArgs(
                "--parallel", "N",
                turbo::str_format("number of parallel sequences to decode (default: %d)", params.n_parallel),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.n_parallel, args.help);
                }
        ).set_env("LLAMA_ARG_N_PARALLEL"));
        ctx_arg.add_option(AppArgs(
                "--sequences", "N",
                turbo::str_format("number of sequences to decode (default: %d)", params.n_sequences),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.n_sequences, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_PARALLEL}));
        ctx_arg.add_option(AppArgs(
                "--cont-batching",
                turbo::str_format("enable continuous batching (a.k.a dynamic batching) (default: %s)",
                                  params.cont_batching ? "enabled" : "disabled"),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.cont_batching = true;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_CONT_BATCHING"));
        ctx_arg.add_option(AppArgs(
                "--no-cont-batching",
                "disable continuous batching",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.cont_batching = false;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_NO_CONT_BATCHING"));
        ctx_arg.add_option(AppArgs(
                "--mmproj", "FILE",
                "path to a multimodal projector file for LLaVA. see examples/llava/README.md",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.mmproj, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_LLAVA}));
        ctx_arg.add_option(AppArgs(
                "--image", "FILE",
                "path to an image file. use with multimodal models. Specify multiple times for batching",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.image, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_LLAVA}));
        if (llama_supports_rpc()) {
            ctx_arg.add_option(AppArgs(
                    "--rpc", "SERVERS",
                    "comma separated list of RPC servers",
                    [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                        app->add_option(args.args, params.rpc_servers, args.help);
                    }
            ).set_env("LLAMA_ARG_RPC"));
        }
        ctx_arg.add_option(AppArgs(
                "--mlock",
                "force system to keep model in RAM rather than swapping or compressing",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.use_mlock = true;
                    }, args.help);
                }
        ).set_env("LLAMA_ARG_MLOCK"));
        ctx_arg.add_option(AppArgs(
                "--no-mmap",
                "do not memory-map model (slower load but may reduce pageouts if not using mlock)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.use_mmap = false;
                    }, args.help);
                }
        ).set_env("LLAMA_ARG_NO_MMAP"));
        ctx_arg.add_option(AppArgs(
                "--numa", "TYPE",
                "attempt optimizations that help on some NUMA systems\n"
                "- distribute: spread execution evenly over all nodes\n"
                "- isolate: only spawn threads on CPUs on the node that execution started on\n"
                "- numactl: use the CPU map provided by numactl\n"
                "if run without this previously, it is recommended to drop the system page cache before using this\n"
                "see https://github.com/ggerganov/llama.cpp/issues/1437",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              if (value == "distribute" || value ==
                                                                                           "") { params.numa = GGML_NUMA_STRATEGY_DISTRIBUTE; }
                                                              else if (value ==
                                                                       "isolate") { params.numa = GGML_NUMA_STRATEGY_ISOLATE; }
                                                              else if (value ==
                                                                       "numactl") { params.numa = GGML_NUMA_STRATEGY_NUMACTL; }
                                                              else { throw std::invalid_argument("invalid value"); }
                                                          },
                                                          args.help
                    );
                }
                /**/
        ).set_env("LLAMA_ARG_NUMA"));
        ctx_arg.add_option(AppArgs(
                "--n-gpu-layers", "N",
                "number of layers to store in VRAM",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<int32_t>(args.args,
                                                      [&params](const int32_t &value) {
                                                          params.n_gpu_layers = value;
                                                          if (!llama_supports_gpu_offload()) {
                                                              fprintf(stderr,
                                                                      "warning: not compiled with GPU offload support, --gpu-layers option will be ignored\n");
                                                              fprintf(stderr,
                                                                      "warning: see main README.md for information on enabling GPU BLAS support\n");
                                                          }
                                                      },
                                                      args.help
                    );
                }
        ).set_env("LLAMA_ARG_N_GPU_LAYERS"));
        ctx_arg.add_option(AppArgs(
                "--gpu-layers-draft", "N",
                "number of layers to store in VRAM for the draft model",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<int32_t>(args.args,
                                                      [&params](const int32_t &value) {
                                                          params.n_gpu_layers_draft = value;
                                                          if (!llama_supports_gpu_offload()) {
                                                              fprintf(stderr,
                                                                      "warning: not compiled with GPU offload support, --gpu-layers-draft option will be ignored\n");
                                                              fprintf(stderr,
                                                                      "warning: see main README.md for information on enabling GPU BLAS support\n");
                                                          }
                                                      },
                                                      args.help
                    );
                }
        ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
        ctx_arg.add_option(AppArgs(
                "--split-mode", "{none,layer,row}",
                "how to split the model across multiple GPUs, one of:\n"
                "- none: use one GPU only\n"
                "- layer (default): split layers and KV across GPUs\n"
                "- row: split rows across GPUs",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              std::string arg_next = value;
                                                              if (arg_next == "none") {
                                                                  params.split_mode = LLAMA_SPLIT_MODE_NONE;
                                                              } else if (arg_next == "layer") {
                                                                  params.split_mode = LLAMA_SPLIT_MODE_LAYER;
                                                              } else if (arg_next == "row") {
#ifdef GGML_USE_SYCL
                                                                  fprintf(stderr, "warning: The split mode value:[row] is not supported by llama.cpp with SYCL. It's developing.\nExit!\n");
                            exit(1);
#endif // GGML_USE_SYCL
                                                                  params.split_mode = LLAMA_SPLIT_MODE_ROW;
                                                              } else {
                                                                  throw std::invalid_argument("invalid value");
                                                              }
                                                              if (!llama_supports_gpu_offload()) {
                                                                  fprintf(stderr,
                                                                          "warning: llama.cpp was compiled without support for GPU offload. Setting the split mode has no effect.\n");
                                                              }
                                                          },
                                                          args.help
                    );
                }
        ).set_env("LLAMA_ARG_SPLIT_MODE"));
        ctx_arg.add_option(AppArgs(
                "--tensor-split", "N0,N1,N2,...",
                "fraction of the model to offload to each GPU, comma-separated list of proportions, e.g. 3,1",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              std::string arg_next = value;

                                                              // split string by , and /
                                                              const std::regex regex{R"([,/]+)"};
                                                              std::sregex_token_iterator it{arg_next.begin(),
                                                                                            arg_next.end(), regex, -1};
                                                              std::vector<std::string> split_arg{it, {}};
                                                              if (split_arg.size() >= llama_max_devices()) {
                                                                  throw std::invalid_argument(
                                                                          turbo::str_format(
                                                                                  "got %d input configs, but system only has %d devices",
                                                                                  (int) split_arg.size(),
                                                                                  (int) llama_max_devices())
                                                                  );
                                                              }
                                                              for (size_t i = 0; i < llama_max_devices(); ++i) {
                                                                  if (i < split_arg.size()) {
                                                                      params.tensor_split[i] = std::stof(split_arg[i]);
                                                                  } else {
                                                                      params.tensor_split[i] = 0.0f;
                                                                  }
                                                              }
                                                              if (!llama_supports_gpu_offload()) {
                                                                  fprintf(stderr,
                                                                          "warning: llama.cpp was compiled without support for GPU offload. Setting a tensor split has no effect.\n");
                                                              }
                                                          },
                                                          args.help
                    );
                }
        ).set_env("LLAMA_ARG_TENSOR_SPLIT"));
        ctx_arg.add_option(AppArgs(
                "--main-gpu", "INDEX",
                turbo::str_format(
                        "the GPU to use for the model (with split-mode = none), or for intermediate results and KV (with split-mode = row) (default: %d)",
                        params.main_gpu),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              params.main_gpu = std::atoi(value.c_str());
                                                              if (!llama_supports_gpu_offload()) {
                                                                  fprintf(stderr,
                                                                          "warning: llama.cpp was compiled without support for GPU offload. Setting the main GPU has no effect.\n");
                                                              }
                                                          },
                                                          args.help
                    );
                }
        ).set_env("LLAMA_ARG_MAIN_GPU"));
        ctx_arg.add_option(AppArgs(
                "--check-tensors",
                turbo::str_format("check model tensor data for invalid values (default: %s)",
                                  params.check_tensors ? "true" : "false"),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.check_tensors = true;
                    }, args.help);
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--override-kv", "KEY=TYPE:VALUE",
                "advanced option to override model metadata by key. may be specified multiple times.\n"
                "types: int, float, bool, str. example: --override-kv tokenizer.ggml.add_bos_token=bool:false",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              if (!string_parse_kv_override(value.c_str(),
                                                                                            params.kv_overrides)) {
                                                                  throw std::runtime_error(
                                                                          turbo::str_format(
                                                                                  "error: Invalid type for KV override: %s\n",
                                                                                  value.c_str()));
                                                              }
                                                          },
                                                          args.help
                    );
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--lora", "FNAME",
                "path to LoRA adapter (can be repeated to use multiple adapters)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::vector<std::string>>(args.args,
                                                                       [&params](
                                                                               const std::vector<std::string> &value) {
                                                                           for (auto &it: value) {
                                                                               params.lora_adapters.push_back(
                                                                                       {std::string(it), 1.0});
                                                                           }

                                                                       },
                                                                       args.help
                    );
                }
                // we define this arg on both COMMON and EXPORT_LORA, so when showing help message of export-lora, it will be categorized as "example-specific" arg
        ).set_examples({LLAMA_EXAMPLE_COMMON, LLAMA_EXAMPLE_EXPORT_LORA}));
        ctx_arg.add_option(AppArgs(
                "--lora-scaled", "FNAME:SCALE",
                "path to LoRA adapter with user defined scaling (can be repeated to use multiple adapters)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::vector<std::string>>(args.args,
                                                                       [&params](
                                                                               const std::vector<std::string> &value) {
                                                                           for (auto &it: value) {
                                                                               std::vector<std::string> kv = turbo::str_split(
                                                                                       it, ":", turbo::SkipEmpty());
                                                                               if (kv.size() == 1) {
                                                                                   params.lora_adapters.push_back(
                                                                                           {std::string(kv[0]), 1.0});
                                                                               } else if (kv.size() == 2) {
                                                                                   params.lora_adapters.push_back(
                                                                                           {std::string(kv[0]),
                                                                                            std::stof(kv[1].c_str())});
                                                                               }

                                                                           }

                                                                       },
                                                                       args.help
                    );
                }
                // we define this arg on both COMMON and EXPORT_LORA, so when showing help message of export-lora, it will be categorized as "example-specific" arg
        ).set_examples({LLAMA_EXAMPLE_COMMON, LLAMA_EXAMPLE_EXPORT_LORA}));
        ctx_arg.add_option(AppArgs(
                "--control-vector", "FNAME",
                "add a control vector\nnote: this argument can be repeated to add multiple control vectors",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::vector<std::string>>(args.args,
                                                                       [&params](
                                                                               const std::vector<std::string> &value) {
                                                                           for (auto &it: value) {
                                                                               params.control_vectors.push_back(
                                                                                       {1.0f, it});
                                                                           }

                                                                       },
                                                                       args.help
                    );
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--control-vector-scaled", "FNAME", "SCALE",
                "add a control vector with user defined scaling SCALE\n"
                "note: this argument can be repeated to add multiple scaled control vectors",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::vector<std::string>>(args.args,
                                                                       [&params](
                                                                               const std::vector<std::string> &value) {
                                                                           for (auto &it: value) {
                                                                               std::vector<std::string> kv = turbo::str_split(
                                                                                       it, ":", turbo::SkipEmpty());
                                                                               if (kv.size() == 2) {
                                                                                   params.control_vectors.push_back(
                                                                                           {std::stof(kv[1]), kv[0]});
                                                                               } else {
                                                                                   throw std::runtime_error(
                                                                                           turbo::str_format(
                                                                                                   "error: Invalid type for control vector: %s\n",
                                                                                                   it.c_str()));
                                                                               }

                                                                           }

                                                                       },
                                                                       args.help
                    );
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--control-vector-layer-range", "START", "END",
                "layer range to apply the control vector(s) to, start and end inclusive",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::vector<std::string>>(args.args,
                                                                       [&params](
                                                                               const std::vector<std::string> &value) {
                                                                           if (value.size() != 2) {
                                                                               throw std::runtime_error(
                                                                                       turbo::str_format(
                                                                                               "error: Invalid type for control vector: %s %s\n",
                                                                                               value[0].c_str(),
                                                                                               value[1].c_str()));
                                                                           }
                                                                           params.control_vector_layer_start = std::stoi(
                                                                                   value[0]);
                                                                           params.control_vector_layer_end = std::stoi(
                                                                                   value[1]);

                                                                       },
                                                                       args.help
                    );
                }
        ));
        ctx_arg.add_option(AppArgs(
                "--alias", "STRING",
                "set alias for model name (to be used by REST API)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.model_alias, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_ALIAS"));
        ctx_arg.add_option(AppArgs(
                "-m, --model", "FNAME",
                ex == LLAMA_EXAMPLE_EXPORT_LORA
                ? std::string("model path from which to load base model")
                : turbo::str_format(
                        "model path (default: `models/$filename` with filename from `--hf-file` "
                        "or `--model-url` if set, otherwise %s)", DEFAULT_MODEL_PATH
                ),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.model, args.help)->required();
                }
        ).set_examples({LLAMA_EXAMPLE_COMMON, LLAMA_EXAMPLE_EXPORT_LORA}).set_env("LLAMA_ARG_MODEL"));
        ctx_arg.add_option(AppArgs(
                "--model-draft", "FNAME",
                "draft model for speculative decoding (default: unused)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.model_draft, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
        ctx_arg.add_option(AppArgs(
                "--model-url", "MODEL_URL",
                "model download url (default: unused)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.model_url, args.help);
                }
        ).set_env("LLAMA_ARG_MODEL_URL"));
        ctx_arg.add_option(AppArgs(
                "--hf-repo", "REPO",
                "Hugging Face model repository (default: unused)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.hf_repo, args.help);
                }
        ).set_env("LLAMA_ARG_HF_REPO"));
        ctx_arg.add_option(AppArgs(
                "--hf-file", "FILE",
                "Hugging Face model file (default: unused)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.hf_file, args.help);
                }
        ).set_env("LLAMA_ARG_HF_FILE"));
        ctx_arg.add_option(AppArgs(
                "--hf-token", "TOKEN",
                "Hugging Face access token (default: value from HF_TOKEN environment variable)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.hf_token, args.help);
                }
        ).set_env("HF_TOKEN"));
        ctx_arg.add_option(AppArgs(
                "--context-file", "FNAME",
                "file to load context from (repeat to specify multiple files)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              std::ifstream file(value, std::ios::binary);
                                                              if (!file) {
                                                                  throw std::runtime_error(turbo::str_format(
                                                                          "error: failed to open file '%s'\n",
                                                                          value.c_str()));
                                                              }
                                                              params.context_files.push_back(value);

                                                          },
                                                          args.help
                    );
                }
        ).set_examples({LLAMA_EXAMPLE_RETRIEVAL}));
        ctx_arg.add_option(AppArgs(
                "--chunk-size", "N",
                turbo::str_format("minimum length of embedded text chunks (default: %d)", params.chunk_size),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.chunk_size, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_RETRIEVAL}));
        ctx_arg.add_option(AppArgs(
                "--chunk-separator", "STRING",
                turbo::str_format("separator between chunks (default: '%s')", params.chunk_separator.c_str()),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.chunk_separator, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_RETRIEVAL}));
        ctx_arg.add_option(AppArgs(
                "--junk", "N",
                turbo::str_format("number of times to repeat the junk text (default: %d)", params.n_junk),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.n_junk, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_PASSKEY}));
        ctx_arg.add_option(AppArgs(
                "--pos", "N",
                turbo::str_format("position of the passkey in the junk text (default: %d)", params.i_pos),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.i_pos, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_PASSKEY}));
        ctx_arg.add_option(AppArgs(
                "-o,--output", "FNAME",
                turbo::str_format("output file (default: '%s')",
                                  ex == LLAMA_EXAMPLE_EXPORT_LORA
                                  ? params.lora_outfile.c_str()
                                  : ex == LLAMA_EXAMPLE_CVECTOR_GENERATOR
                                    ? params.cvector_outfile.c_str()
                                    : params.out_file.c_str()),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              params.out_file = value;
                                                              params.cvector_outfile = value;
                                                              params.lora_outfile = value;
                                                          },
                                                          args.help
                    );

                }
        ).set_examples({LLAMA_EXAMPLE_IMATRIX, LLAMA_EXAMPLE_CVECTOR_GENERATOR, LLAMA_EXAMPLE_EXPORT_LORA}));
        ctx_arg.add_option(AppArgs(
                "--output-frequency", "N",
                turbo::str_format("output the imatrix every N iterations (default: %d)", params.n_out_freq),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.n_out_freq, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_IMATRIX}));
        ctx_arg.add_option(AppArgs(
                "--save-frequency", "N",
                turbo::str_format("save an imatrix copy every N iterations (default: %d)", params.n_save_freq),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.n_save_freq, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_IMATRIX}));
        ctx_arg.add_option(AppArgs(
                "--process-output",
                turbo::str_format("collect data for the output tensor (default: %s)",
                                  params.process_output ? "true" : "false"),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.process_output = true;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_IMATRIX}));
        ctx_arg.add_option(AppArgs(
                "--no-ppl",
                turbo::str_format("do not compute perplexity (default: %s)", params.compute_ppl ? "true" : "false"),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.compute_ppl = false;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_IMATRIX}));
        ctx_arg.add_option(AppArgs(
                "--chunk", "N",
                turbo::str_format("start processing the input from chunk N (default: %d)", params.i_chunk),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.i_chunk, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_IMATRIX}));
        ctx_arg.add_option(AppArgs(
                "--pps",
                turbo::str_format("is the prompt shared across parallel sequences (default: %s)",
                                  params.is_pp_shared ? "true" : "false"),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.is_pp_shared = true;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_BENCH}));
        ctx_arg.add_option(AppArgs(
                "--npp", "n0,n1,...",
                "number of prompt tokens",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.n_pp, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_BENCH}));
        ctx_arg.add_option(AppArgs(
                "--ntg", "n0,n1,...",
                "number of text generation tokens",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.n_tg, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_BENCH}));
        ctx_arg.add_option(AppArgs(
                "--npl", "n0,n1,...",
                "number of parallel prompts",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.n_pl, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_BENCH}));
        ctx_arg.add_option(AppArgs(
                "--embd-normalize", "N",
                turbo::str_format(
                        "normalisation for embeddings (default: %d) (-1=none, 0=max absolute int16, 1=taxicab, 2=euclidean, >2=p-norm)",
                        params.embd_normalize),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.embd_normalize, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_EMBEDDING}));
        ctx_arg.add_option(AppArgs(
                "--embd-output-format", "FORMAT",
                "empty = default, \"array\" = [[],[]...], \"json\" = openai style, \"json+\" = same \"json\" + cosine similarity matrix",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.embd_out, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_EMBEDDING}));
        ctx_arg.add_option(AppArgs(
                "--embd-separator", "STRING",
                "separator of embeddings (default \\n) for example \"<#sep#>\"",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.embd_sep, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_EMBEDDING}));
        ctx_arg.add_option(AppArgs(
                "--host", "HOST",
                turbo::str_format("ip address to listen (default: %s)", params.hostname.c_str()),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.hostname, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_HOST"));
        ctx_arg.add_option(AppArgs(
                "--port", "PORT",
                turbo::str_format("port to listen (default: %d)", params.port),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.port, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_PORT"));
        ctx_arg.add_option(AppArgs(
                "--path", "PATH",
                turbo::str_format("path to serve static files from (default: %s)", params.public_path.c_str()),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.public_path, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_STATIC_PATH"));
        ctx_arg.add_option(AppArgs(
                "--embedding",
                turbo::str_format(
                        "restrict to only support embedding use case; use only with dedicated embedding models (default: %s)",
                        params.embedding ? "enabled" : "disabled"),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.embedding = true;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_EMBEDDINGS"));
        ctx_arg.add_option(AppArgs(
                "--rerank",
                turbo::str_format("enable reranking endpoint on server (default: %s)",
                                  params.reranking ? "enabled" : "disabled"),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.reranking = true;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_RERANKING"));
        ctx_arg.add_option(AppArgs(
                "--api-key", "KEY",
                "API key to use for authentication (default: none)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.api_keys, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_API_KEY"));
        ctx_arg.add_option(AppArgs(
                "--api-key-file", "FNAME",
                "path to file containing API keys (default: none)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              std::ifstream key_file(value);
                                                              if (!key_file) {
                                                                  throw std::runtime_error(turbo::str_format(
                                                                          "error: failed to open file '%s'\n",
                                                                          value.c_str()));
                                                              }
                                                              std::string key;
                                                              while (std::getline(key_file, key)) {
                                                                  if (!key.empty()) {
                                                                      params.api_keys.push_back(key);
                                                                  }
                                                              }
                                                              key_file.close();
                                                          },
                                                          args.help
                    );
                }
        ).set_examples({LLAMA_EXAMPLE_SERVER}));
        ctx_arg.add_option(AppArgs(
                "--ssl-key-file", "FNAME",
                "path to file a PEM-encoded SSL private key",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.ssl_file_key, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_SSL_KEY_FILE"));
        ctx_arg.add_option(AppArgs(
                "--ssl-cert-file", "FNAME",
                "path to file a PEM-encoded SSL certificate",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.ssl_file_cert, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_SSL_CERT_FILE"));
        ctx_arg.add_option(AppArgs(
                "--timeout", "N",
                turbo::str_format("server read/write timeout in seconds (default: %d)", params.timeout_read),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<int32_t>(args.args,
                                                      [&params](const int32_t &value) {
                                                          params.timeout_read = value;
                                                          params.timeout_write = value;
                                                      },
                                                      args.help
                    );
                }
        ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_TIMEOUT"));
        ctx_arg.add_option(AppArgs(
                "--threads-http", "N",
                turbo::str_format("number of threads used to process HTTP requests (default: %d)",
                                  params.n_threads_http),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.n_threads_http, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_THREADS_HTTP"));
        ctx_arg.add_option(AppArgs(
                "--cache-reuse", "N",
                turbo::str_format("min chunk size to attempt reusing from the cache via KV shifting (default: %d)",
                                  params.n_cache_reuse),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.n_cache_reuse, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_CACHE_REUSE"));
        ctx_arg.add_option(AppArgs(
                "--metrics",
                turbo::str_format("enable prometheus compatible metrics endpoint (default: %s)",
                                  params.endpoint_metrics ? "enabled" : "disabled"),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.endpoint_metrics = true;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_ENDPOINT_METRICS"));
        ctx_arg.add_option(AppArgs(
                "--slots",
                turbo::str_format("enable slots monitoring endpoint (default: %s)",
                                  params.endpoint_slots ? "enabled" : "disabled"),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.endpoint_slots = true;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_ENDPOINT_SLOTS"));
        ctx_arg.add_option(AppArgs(
                "--props",
                turbo::str_format("enable changing global properties via POST /props (default: %s)",
                                  params.endpoint_props ? "enabled" : "disabled"),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.endpoint_props = true;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_ENDPOINT_PROPS"));
        ctx_arg.add_option(AppArgs(
                "--no-slots",
                "disables slots monitoring endpoint",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.endpoint_slots = false;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_NO_ENDPOINT_SLOTS"));
        ctx_arg.add_option(AppArgs(
                "--slot-save-path", "PATH",
                "path to save slot kv cache (default: disabled)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              params.slot_save_path = value;
                                                              // if doesn't end with DIRECTORY_SEPARATOR, add it
                                                              if (!params.slot_save_path.empty() &&
                                                                  params.slot_save_path[params.slot_save_path.size() -
                                                                                        1] != DIRECTORY_SEPARATOR) {
                                                                  params.slot_save_path += DIRECTORY_SEPARATOR;
                                                              }
                                                          },
                                                          args.help
                    );

                }
        ).set_examples({LLAMA_EXAMPLE_SERVER}));
        ctx_arg.add_option(AppArgs(
                "--chat-template", "JINJA_TEMPLATE",
                "set custom jinja chat template (default: template taken from model's metadata)\n"
                "if suffix/prefix are specified, template will be disabled\n"
                "only commonly used templates are accepted:\nhttps://github.com/ggerganov/llama.cpp/wiki/Templates-supported-by-llama_chat_apply_template",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              if (!KMContext::chat_verify_template(value)) {
                                                                  throw std::runtime_error(turbo::str_format(
                                                                          "error: the supplied chat template is not supported: %s\n"
                                                                          "note: llama.cpp does not use jinja parser, we only support commonly used templates\n",
                                                                          value.c_str()
                                                                  ));
                                                              }
                                                              params.chat_template = value;
                                                          },
                                                          args.help
                    );

                }
        ).set_examples({LLAMA_EXAMPLE_MAIN, LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_CHAT_TEMPLATE"));
        ctx_arg.add_option(AppArgs(
                "--slot-prompt-similarity", "SIMILARITY",
                turbo::str_format(
                        "how much the prompt of a request must match the prompt of a slot in order to use that slot (default: %.2f, 0.0 = disabled)\n",
                        params.slot_prompt_similarity),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.slot_prompt_similarity, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SERVER}));
        ctx_arg.add_option(AppArgs(
                "--lora-init-without-apply",
                turbo::str_format(
                        "load LoRA adapters without applying them (apply later via POST /lora-adapters) (default: %s)",
                        params.lora_init_without_apply ? "enabled" : "disabled"),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.lora_init_without_apply = true;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_SERVER}));
        ctx_arg.add_option(AppArgs(
                "--simple-io",
                "use basic IO for better compatibility in subprocesses and limited consoles",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_flag(args.args, [&params](int64_t) {
                        params.simple_io = true;
                    }, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_MAIN, LLAMA_EXAMPLE_INFILL}));
        ctx_arg.add_option(AppArgs(
                "--positive-file", "FNAME",
                turbo::str_format("positive prompts file, one prompt per line (default: '%s')",
                                  params.cvector_positive_file.c_str()),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.cvector_positive_file, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_CVECTOR_GENERATOR}));
        ctx_arg.add_option(AppArgs(
                "--negative-file", "FNAME",
                turbo::str_format("negative prompts file, one prompt per line (default: '%s')",
                                  params.cvector_negative_file.c_str()),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.cvector_negative_file, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_CVECTOR_GENERATOR}));
        ctx_arg.add_option(AppArgs(
                "--pca-batch", "N",
                turbo::str_format(
                        "batch size used for PCA. Larger batch runs faster, but uses more memory (default: %d)",
                        params.n_pca_batch),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.n_pca_batch, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_CVECTOR_GENERATOR}));
        ctx_arg.add_option(AppArgs(
                "--pca-iter", "N",
                turbo::str_format("number of iterations used for PCA (default: %d)", params.n_pca_iterations),
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option(args.args, params.n_pca_iterations, args.help);
                }
        ).set_examples({LLAMA_EXAMPLE_CVECTOR_GENERATOR}));
        ctx_arg.add_option(AppArgs(
                "--method", "{pca, mean}",
                "dimensionality reduction method to be used (default: pca)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              if (value ==
                                                                  "pca") { params.cvector_dimre_method = DIMRE_METHOD_PCA; }
                                                              else if (value ==
                                                                       "mean") { params.cvector_dimre_method = DIMRE_METHOD_MEAN; }
                                                              else { throw std::invalid_argument("invalid value"); }
                                                          },
                                                          args.help
                    );
                }
        ).set_examples({LLAMA_EXAMPLE_CVECTOR_GENERATOR}));
        ctx_arg.add_option(AppArgs(
                "--output-format", "{md,jsonl}",
                "output format for batched-bench results (default: md)",
                [](KMParams &params, turbo::cli::App *app, const AppArgs &args) {
                    app->add_option_function<std::string>(args.args,
                                                          [&params](const std::string &value) {
                                                              if (value ==
                                                                  "jsonl") { params.batched_bench_output_jsonl = true; }
                                                              else if (value ==
                                                                       "md") { params.batched_bench_output_jsonl = false; }
                                                              else { std::invalid_argument("invalid value"); }
                                                          },
                                                          args.help
                    );
                }
        ).set_examples({LLAMA_EXAMPLE_BENCH}));

    }


    ParamsContext ParamsContext::setup_app_context(turbo::cli::App *app, KMParams &p, llama_example ex) {
        ParamsContext ret;
        ret.params = &p;
        params_parser_init(ret, p, ex);
        KMParams &params = *ret.params;
        for (auto it: ret.options) {
            if (!it.app_handler) {
                std::cerr << "error: no app handler set for " << it.args;
                exit(1);
            }
            it.app_handler(*ret.params, app, it);
        }
        auto parse_complete_check = [&params]() {
            postprocess_cpu_params(params.cpuparams, nullptr);
            postprocess_cpu_params(params.cpuparams_batch, &params.cpuparams);
            postprocess_cpu_params(params.draft_cpuparams, &params.cpuparams);
            postprocess_cpu_params(params.draft_cpuparams_batch, &params.cpuparams_batch);

            if (params.prompt_cache_all && (params.interactive || params.interactive_first)) {
                throw std::invalid_argument("error: --prompt-cache-all not supported in interactive mode yet\n");
            }

            common_params_handle_model_default(params);

            if (params.escape) {
                KMContext::string_process_escapes(params.prompt);
                KMContext::string_process_escapes(params.input_prefix);
                KMContext::string_process_escapes(params.input_suffix);
                for (auto &antiprompt: params.antiprompt) {
                    KMContext::string_process_escapes(antiprompt);
                }
                std::vector<std::string> tp;
                for (auto &seq_breaker: params.sparams.dry_sequence_breakers) {
                    std::string word = seq_breaker;
                    KMContext::string_process_escapes(word);
                    tp.push_back(word);
                }
                params.sparams.dry_sequence_breakers = std::move(tp);
            }

            if (!params.kv_overrides.empty()) {
                params.kv_overrides.emplace_back();
                params.kv_overrides.back().key[0] = 0;
            }

            if (params.reranking && params.embedding) {
                throw std::invalid_argument("error: either --embedding or --reranking can be specified, but not both");
            }
        };
        app->parse_complete_callback(parse_complete_check);
        return ret;
    }

}  // namespace kllm

